﻿namespace EasyWeb
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Linq;

    internal static partial class EWHelpers
    {
        public static string ToText(this EWText text)
        {
            var xmlDoc = new XDocument(new XElement("texts"));

            if (text != null)
            {
                foreach (var item in text.Values)
                {
                    var xmlText = new XElement("text", new XAttribute("name", item.Name), new XText(item.Text));

                    xmlDoc.Root.Add(xmlText);
                }
            }

            return xmlDoc.ToString(SaveOptions.DisableFormatting);
        }

        public static EWText ToText(this string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return null;
            }

            var result = new EWText();

            var xmlDoc = XDocument.Parse(xml, LoadOptions.None);

            foreach (var xmlText in xmlDoc.Root.Elements("text"))
            {
                result.Values.Add(new EWTextValue(xmlText.Attribute("name").Value, xmlText.Value));
            }

            return result;
        }
    }
}
